﻿/******************************************************************************
 *  作者：       Maxzhang1985
 *  创建时间：   2012/4/27 17:21:39
 *
 *
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using ExtendPropertyLib.WPF;
using ExtendPropertyLib;
using RadHelper=ExORMDesginer.RadWindow.Helper;
using ExORMDesginer.Helper;
using System.IO;
using System.Xml.Serialization;

using ExORMDesginer.Plugin.Template;
using System.Threading;
using System.Globalization;
namespace ExORMDesginer.Plugin.Wizard
{
    [Export(typeof(IWizard))]
    public class ModelWizard : WizardBase
    {

        #region 基础信息

        public static ExtendProperty CompanyProperty = RegisterProperty<ModelWizard>(v => v.Company);
        /// <summary>
        /// 公司
        /// </summary>
        [WizardMember(Name = "Company", Memo = "公司")]
        public string Company { set { SetValue(CompanyProperty, value); } get { return (string)GetValue(CompanyProperty); } }


        public static ExtendProperty ProjectNameProperty = RegisterProperty<ModelWizard>(v => v.ProjectName);
        /// <summary>
        /// 项目名称
        /// </summary>
        [WizardMember(Name = "ProjectName", Memo = "项目名称")]
        public string ProjectName { set { SetValue(ProjectNameProperty, value); } get { return (string)GetValue(ProjectNameProperty); } }


        public static ExtendProperty NameSpaceProperty = RegisterProperty<ModelWizard>(v => v.NameSpace);
        /// <summary>
        /// 命名空间
        /// </summary>
        [WizardMember(Name = "NameSpace", Memo = "命名空间")]
        public string NameSpace { set { SetValue(NameSpaceProperty, value); } get { return (string)GetValue(NameSpaceProperty); } }


        public static ExtendProperty AuthorProperty = RegisterProperty<ModelWizard>(v => v.Author);
        /// <summary>
        /// 作者
        /// </summary>
        [WizardMember(Name = "Author", Memo = "作者")]
        public string Author { set { SetValue(AuthorProperty, value); } get { return (string)GetValue(AuthorProperty); } }


        public static ExtendProperty CreateDateProperty = RegisterProperty<ModelWizard>(v => v.CreateDate);
        /// <summary>
        /// 创建日期
        /// </summary>
        [WizardMember(Name = "CreateDate", Memo = "创建日期")]
        public DateTime CreateDate { set { SetValue(CreateDateProperty, value); } get { return (DateTime)GetValue(CreateDateProperty); } }

        public static ExtendProperty IsSomeProperty = RegisterProperty<ModelWizard>(v => v.IsBatch);
        /// <summary>
        /// 是否批量生成
        /// </summary>
        [WizardMember(Name = "IsBatch", Memo = "是否批量生成")]
        public bool IsBatch { set { SetValue(IsSomeProperty, value); } get { return (bool)GetValue(IsSomeProperty); } }


        public static ExtendProperty FrontNameFixProperty = RegisterProperty<ModelWizard>(v => v.FrontNameFix);
        /// <summary>
        /// 模型名称前缀
        /// </summary>
        public string FrontNameFix { set { SetValue(FrontNameFixProperty, value); } get { return (string)GetValue(FrontNameFixProperty); } }



        public static ExtendProperty BackNameFixProperty = RegisterProperty<ModelWizard>(v => v.BackNameFix);
        /// <summary>
        /// 模型名称后缀
        /// </summary>
        public string BackNameFix { set { SetValue(BackNameFixProperty, value); } get { return (string)GetValue(BackNameFixProperty); } }


        public static ExtendProperty FirstWordToUpperProperty = RegisterProperty<ModelWizard>(v => v.FirstWordToUpper);
        /// <summary>
        /// 首字母是否大写
        /// </summary>
        public bool FirstWordToUpper { set { SetValue(FirstWordToUpperProperty, value); } get { return (bool)GetValue(FirstWordToUpperProperty); } }


        public static ExtendProperty ReplaceSpaceWithUnderscoreProperty = RegisterProperty<ModelWizard>(v => v.ReplaceSpaceWithUnderscore);
        /// <summary>
        /// 是否替换模型名称中的空格为下划线
        /// </summary>
        public bool ReplaceSpaceWithUnderscore { set { SetValue(ReplaceSpaceWithUnderscoreProperty, value); } get { return (bool)GetValue(ReplaceSpaceWithUnderscoreProperty); } }


        private VelocityHelper vh = new VelocityHelper(templatePath);
      
        private void setTemplateMember()
        {
            vh.Put("Entity", Model);

            var query = from p in this.GetType().GetProperties()
                        let member = p.GetCustomAttributes(typeof(WizardMemberAttribute), false).Length > 0 ? p.GetCustomAttributes(typeof(WizardMemberAttribute), false)[0] as WizardMemberAttribute : null
                        where member != null
                        select new { Property = p, MemberAttribute = member };

            foreach (var q in query)
            {
                vh.Put(q.MemberAttribute.Name, q.Property.GetValue(this, null));
            }
        }

        #endregion

        /// <summary>
        /// 单对象输出
        /// </summary>
        /// <returns></returns>
        public string GetTemplateResult()
        {

            SetModelState(Model);

            setTemplateMember();

            return vh.GetResult(this.TemplateInfo.FileName);
        }


        public string GetMoreTemplateResult()
        {
            setTemplateMember();
            List<DbEntity> DbEntitys = null;
            if (TemplateInfo.TemplateType == EntityType.StoredProcedure)
            {
                DbEntitys = Host.Tables.Where(t => t.EntityViewType == EntityType.StoredProcedure).ToList();
            }
            else
            {
                DbEntitys = Host.Tables.Where(t => t.EntityViewType == EntityType.Table || t.EntityViewType == EntityType.View).ToList();
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("/******************************************************************************");
            sb.AppendFormat("*  作者:        {0}{1}",this.Author,Environment.NewLine);
            sb.AppendFormat("*  公司:        {0}{1}", this.Company, Environment.NewLine);
            sb.AppendFormat("*  项目名称:    {0}{1}", this.ProjectName, Environment.NewLine);
            sb.AppendFormat("*  创建时间:    {0}{1}", this.CreateDate.ToString(), Environment.NewLine);
               sb.AppendLine("*  ");
               sb.AppendLine("*  ");
               sb.AppendLine("******************************************************************************/");
            sb.AppendLine();
            sb.AppendLine("using System;");
            sb.AppendLine("using ExtendPropertyLib;");
            sb.AppendLine("using using MaxZhang.EasyEntities.Persistence;");
            sb.AppendLine("using MaxZhang.EasyEntities.Persistence.Mapping;");
            sb.AppendLine();
            sb.Append("namespace ").Append(NameSpace).AppendLine();
            sb.AppendLine("{");
            foreach (var Entity in DbEntitys)
            {
                SetModelState(Entity);
                vh.Put("Entity", Entity);
                var templateString = vh.GetResult(this.TemplateInfo.FileName);
                sb.AppendLine(templateString);

            }
            sb.AppendLine("}");

            return sb.ToString();
        }


        private void SetModelState(DbEntity entity)
        {
            if (FirstWordToUpper)
            {
                TextInfo tInfo = Thread.CurrentThread.CurrentCulture.TextInfo;
                entity.Name = tInfo.ToTitleCase(entity.Name);
                foreach (var p in entity.Propertys)
                {
                    p.Name = tInfo.ToTitleCase(p.Name);
                }


            }
            if (ReplaceSpaceWithUnderscore)
            {
                entity.Name = entity.Name.Replace(' ', '_');
            }
        }
    
        /// <summary>
        /// 模板处理方法
        /// </summary>
        /// <returns></returns>
        public override string Process()
        {
            IWindowManager wm = Host.WindowManager;
            var UIViewModel = ViewModelFactory.GetModel<CodeWizardUIViewModel>();
            UIViewModel.Model = this;
            wm.ShowDialog(UIViewModel);
            return UIViewModel.Result;
        }


        public override string Name
        {
            get { return "ModelWizard"; }
        }

        #region 持久化
        
        #region FIle BasePath

        private static string basePath = AppDomain.CurrentDomain.BaseDirectory;
        private static string templatePath = Path.Combine(basePath, "ItemTemplate");
        private static string configPath = Path.Combine(templatePath, "ModelWizard.cfg");
        #endregion
        public void SaveInfo()
        {
             File.WriteAllText(configPath,  this.Serializer(), Encoding.Default);
        }

        public void LoadInfo()
        {
            string configXml = File.ReadAllText(configPath, Encoding.Default);
            var m = configXml.Deserialize<ModelWizard>();
            if (m != null)
            {
                this.Author = m.Author;
                this.BackNameFix = m.BackNameFix;
                this.Company = m.Company;
                this.CreateDate = DateTime.Now;
                this.FirstWordToUpper = m.FirstWordToUpper;
                this.FrontNameFix = m.FrontNameFix;
                this.NameSpace = m.NameSpace;
                this.ProjectName = m.ProjectName;
                this.ReplaceSpaceWithUnderscore = m.ReplaceSpaceWithUnderscore;
            }
        }
        #endregion

       


    
    }
}
